<template>
  <common-list>
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="65px"
        @submit.native.prevent
      >
        <!-- <el-form-item label="告警子类型" prop="alarmBusiness">
          <el-select v-model="queryParams.alarmBusiness" clearable>
            <el-option label="全部" :value="null"></el-option>
            <el-option
              v-for="item in alarmTypeOption"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="告警类型" prop="alarmType">
          <el-select v-model="queryParams.alarmType" clearable>
            <el-option label="全部" :value="null"></el-option>
            <el-option
              v-for="item in alarmTypeOption"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="告警等级" prop="alarmLevel">
          <el-select v-model="queryParams.alarmLevel" filterable>
            <el-option label="全部" :value="null"></el-option>
            <el-option
              v-for="item in alarmLevelOption"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </common-search>
    <div slot="tools">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            @click="handleAdd"
            v-hasPermi="['config:template:add']"
            >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['config:template:remove']"
            >批量删除
          </el-button>
        </el-col>
      </el-row>
    </div>
    <common-table
      slot="content"
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="告警类型" align="left" prop="alarmTypeName" />
      <el-table-column
        label="告警等级"
        align="left"
        prop="alarmLevelName"
        width="80"
      />
      <!-- <el-table-column
        label="告警子类型"
        align="left"
        prop="alarmBusinessName"
      /> -->
      <el-table-column
        label="告警模板"
        align="left"
        prop="alarmTemplate"
        show-overflow-tooltip
      />
      <el-table-column
        label="短信模板"
        align="left"
        prop="smsTemplate"
        show-overflow-tooltip
      />
      <el-table-column
        label="邮件模板"
        align="left"
        prop="emailTemplate"
        show-overflow-tooltip
      />
      <el-table-column
        label="系统消息模板"
        align="left"
        prop="messageTemplate"
        show-overflow-tooltip
      />
      <el-table-column
        label="备注"
        align="left"
        prop="remark"
        show-overflow-tooltip
      />
      <el-table-column
        label="操作"
        align="left"
        width="90"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['config:template:edit']"
            >编辑
          </el-button>
          <el-button
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['config:template:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </common-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改告警模板列对话框 -->
    <common-edit-dialog
      :title="title"
      :visible.sync="open"
      @cancel="cancel"
      @submit="submitForm"
      :button-loading="isloging"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="90px"
        @submit.native.prevent
      >
        <el-row :gutter="18">
          <el-col :span="12">
            <el-form-item label="告警类型" prop="alarmType">
              <el-select
                v-model="form.alarmType"
                placeholder="请选择"
                filterable
                clearable
                @change="alarmTypeChange(form.alarmType)"
              >
                <el-option
                  v-for="item in alarmTypeOption"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="告警等级  " prop="alarmLevel">
              <el-select
                v-model="form.alarmLevel"
                placeholder="请选择"
                clearable
                filterable
              >
                <el-option
                  v-for="item in alarmLevelOption"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="告警子类型" prop="alarmBusiness">
              <el-select
                v-model="form.alarmBusiness"
                placeholder="请选择"
                clearable
                filterable
              >
                <el-option
                  v-for="item in sysAlarmBusinessList"
                  :key="item.id"
                  :label="item.alarmBusiness"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item> -->
          </el-col>
          <el-col :span="24">
            <el-form-item label="告警模板" prop="alarmTemplate">
              <div style="width: 100%; height: 120px">
                <code-editor
                  key="alarm-template-editor"
                  v-model="form.alarmTemplate"
                  :variable="variable"
                  placeholder="变量示例: &{userName}; 只支持英文状态的&符号"
                ></code-editor>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="短信模板" prop="smsTemplate">
              <div style="width: 100%; height: 120px">
                <code-editor
                  key="sms-template-editor"
                  v-model="form.smsTemplate"
                  :variable="variable"
                  placeholder="变量示例: &{userName}; 只支持英文状态的&符号"
                ></code-editor>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="邮件模板" prop="emailTemplate">
              <div style="width: 100%; height: 120px">
                <code-editor
                  key="email-template-editor"
                  v-model="form.emailTemplate"
                  :variable="variable"
                  placeholder="变量示例: &{userName}; 只支持英文状态的&符号"
                ></code-editor>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="系统消息模板" prop="messageTemplate">
              <div style="width: 100%; height: 120px">
                <code-editor
                  key="message-template-editor"
                  v-model="form.messageTemplate"
                  :variable="variable"
                  placeholder="变量示例: &{userName}; 只支持英文状态的&符号"
                ></code-editor>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <common-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </common-edit-dialog>
  </common-list>
</template>

<script>
import {
  listTemplate,
  getTemplate,
  delTemplate,
  addTemplate,
  updateTemplate,
} from "@/api/system/alarmtemplate";
import {
  alarmCodeGetAlarmType,
  alarmCodeGetAlarmLevel,
  businessList,
} from "@/api/system/alarmCode";
import CodeEditor from "@/components/CodeEditor";
import { getAlarmParam } from "@/api/system";
import BaseList from "@/mixins/BaseList";

export default {
  name: "Template",
  mixins: [BaseList],
  components: {
    CodeEditor,
  },
  data() {
    return {
      alarmLevelOption: [],
      alarmTypeOption: [],
      sysAlarmBusinessList: [],
      isloging: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 告警模板列表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      alarmTemplate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        alarmType: "",
        alarmLevel: "",
        alarmTemplate: "",
        alarmTypeName: "",
        alarmLevelName: "",
        smsTemplate: "",
        emailTemplate: "",
        messageTemplate: "",
        alarmBusiness: "",
      },
      // 表单参数
      form: {
        id: "",
        alarmType: "",
        alarmLevel: "",
        alarmTemplate: "",
        smsTemplate: "",
        emailTemplate: "",
        messageTemplate: "",
        alarmBusiness: "",
        status: "0",
        createTime: "",
        updateTime: "",
        createBy: "",
        updateBy: "",
        remark: "",
      },
      // 表单校验
      rules: {
        alarmBusiness: [
          {
            required: true,
            message: "请选择告警子类型",
            trigger: "blur",
          },
        ],
        alarmType: [
          { required: true, message: "请选择告警类型", trigger: "change" },
        ],
        alarmLevel: [
          {
            required: true,
            message: "请选择告警等级",
            trigger: "blur",
          },
        ],
        alarmTemplate: [
          { required: true, message: "请输入告警模板", trigger: "blur" },
        ],
      },
      variable: [],
    };
  },
  created() {
    this.getAlarmLevelNameById();
    this.getAlarmLevelNameById();
    this.getAlarmLevel();
    this.getAlarmType();
    this.getList();
    this.getAlarmParam();
  },
  methods: {
    getAlarmParam() {
      getAlarmParam().then((res) => {
        if (res?.code === 200) {
          this.variable = res.data.reduce((r, c) => {
            r.push({
              label: c.name,
              value: c.id,
            });
            return r;
          }, []);
        } else {
          this.variable = [];
        }
      });
    },
    /** 查询告警模板列列表 */
    getList() {
      this.loading = true;
      listTemplate(this.queryParams)
        .then((res) => {
          if (res && res.code === 200) {
            this.list = res.rows;
            this.total = res.total;
          } else {
            this.list = [];
            this.total = 0;
            console.log(22);
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 取消按钮
    cancel() {
      this.reset();
      this.open = false;
    },
    // 表单重置
    reset() {
      this.form = {
        id: "",
        alarmType: "",
        alarmLevel: "",
        alarmTemplate: "",
        smsTemplate: "",
        emailTemplate: "",
        messageTemplate: "",
        alarmBusiness: "",
        status: "0",
        createTime: "",
        updateTime: "",
        createBy: "",
        updateBy: "",
        remark: "",
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = this.$options.data().queryParams
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.reset();
      this.title = "新增告警模板";
      this.form.id = "";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.open = true;
      this.title = "编辑告警模板";
      this.reset();
      setTimeout(() => {
        this.$nextTick(() => {
          Reflect.ownKeys(this.form).forEach((k) => (this.form[k] = row[k]));
          this.form.emailTemplate = this.form.emailTemplate
            ? this.form.emailTemplate
            : "";
          this.form.messageTemplate = this.form.messageTemplate
            ? this.form.messageTemplate
            : "";
          this.form.smsTemplate = this.form.smsTemplate
            ? this.form.smsTemplate
            : "";
          this.form.alarmLevel = this.form.alarmLevel.toString();
          this.form.alarmType = this.form.alarmType.toString();
        });
      }, 100);
      this.alarmTypeChange(row.alarmType);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.isloging = true;
          if (this.title === "编辑告警模板") {
            updateTemplate(this.form)
              .then((response) => {
                if (response && response.code === 200) {
                  this.$GlobalSuccessMessage("编辑成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.$GlobalErrorConfirm("编辑失败", response.msg);
                }
              })
              .finally(() => {
                this.isloging = false;
              });
          } else {
            addTemplate(this.form)
              .then((response) => {
                if (response && response.code === 200) {
                  this.$GlobalSuccessMessage("新增成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.$GlobalErrorConfirm("新增失败", response.msg);
                }
              })
              .finally(() => {
                this.isloging = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids.join(",");
      this.$GlobalDeleteConfirm().then(() => {
        delTemplate({ ids }).then((res) => {
          if (res && res.code === 200) {
            this.queryParams.pageNum = 1;
            this.$GlobalSuccessMessage("删除成功");
            if (
              this.queryParams.pageNum > 1 &&
              ids.split(",").length === this.list.length
            ) {
              this.queryParams.pageNum -= 1;
            }
            this.getList();
          } else {
            this.$GlobalErrorConfirm("删除失败", res.msg).then();
          }
        });
      }).catch(()=>{});
    },
    getAlarmType() {
      alarmCodeGetAlarmType().then((res) => {
        this.alarmTypeOption = res.data;
      });
    },
    getAlarmLevel() {
      alarmCodeGetAlarmLevel().then((res) => {
        this.alarmLevelOption = res.data;
      });
    },
    getAlarmLevelNameById(id) {
      let al = this.alarmLevelOption.find(
        (item) => parseInt(item.id) === parseInt(id)
      );
      return al ? al.name : "";
    },
    getAlarmTypeNameById(id) {
      let at = this.alarmTypeOption.find(
        (item) => parseInt(item.id) === parseInt(id)
      );
      return at ? at.name : "";
    },
    alarmTypeChange(row) {
      businessList({ alarmType: row }).then((res) => {
        if (res && res.code === 200) {
          this.sysAlarmBusinessList = res.rows;
        } else {
          this.sysAlarmBusinessList = [];
        }
      });
    },
  },
};
</script>

<style scoped lang="scss"></style>
